package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Customers;
import com.tianxin.workbao.workBao.bean.CustomersDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.StringUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/17.
 */

public class CustomerProvide extends BaseDataProvide {
    private Integer mPage = 1;
    private List<Customers> mCustomers;
    private int isFromServer;
    private UpdateListViewListener mUpdateListViewListener;
    private int cptype;
    private CustomersDao customerDao;


    public CustomerProvide(Context context, UpdateListViewListener listener, int cptype) {
        super(context);
        mUpdateListViewListener = listener;
        isFromServer = 0;
        this.cptype = cptype;
        customerDao = mGreenDaoHelper.getDaoSession().getCustomersDao();
    }

    private void getFromDb() {
        String where = "";
        if (cptype == Constant.CUSTOMER_TYPE_TRANS) {
            where = String.format("cptype = %d ", Constant.CUSTOMER_TYPE_TRANS);
        } else {
            where = String.format("cptype in(%d,%d) AND isis >0 ", cptype, Constant.CUSTOMER_TYPE_TWO);
        }
        Query<Customers> query = customerDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .offset((mPage - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        if (mCustomers != null) {
            mCustomers.clear();
        }
        mCustomers = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    mCustomers = JSON.parseArray(dataJson, Customers.class);
                                    saveToDb(mCustomers);
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("customer To Bean Error :类型转换出错 ");
                            }
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        mUpdateListViewListener.showMessage(information);
                    }

                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    mUpdateListViewListener.showMessage("返回异常：" + reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < mCustomers.size(); i++) {
                customerDao.insertOrReplace(mCustomers.get(i));
            }
        } else {
            customerDao.insertOrReplace((Customers) obj);
        }
    }

    /**
     * get coals 公司信息
     *
     * @param page
     */
    public void getCustomers(int type, int page) {
        mPage = page;
        this.cptype = type;
        getFromDb();
        if (mCustomers == null || mCustomers.isEmpty()) {
            if (isFromServer == 0) {
                updateFromServer();
                getCustomers(cptype, page);
            }
        }
        refreshUI();
    }

    /**
     * update the coal data  from server
     */
    private void updateFromServer() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getCustomerUrl(), params), getDisposeDataHandle());
        }
    }

    @Override
    public void refreshUI() {
        if (mCustomers != null && !mCustomers.isEmpty()) {
            if (mPage > 1) {
                mUpdateListViewListener.onLoadMoreData(mCustomers);
            } else {
                mUpdateListViewListener.onRefreshData(mCustomers);
            }
        } else {
            mUpdateListViewListener.showMessage("没有数据");
        }
    }

    public void getAllCustomers(int companyType) {
        String where = "";
        if (companyType == Constant.CUSTOMER_TYPE_TRANS) {
            where = String.format("cptype = %d ", Constant.CUSTOMER_TYPE_TRANS);
        } else {
            where = String.format("cptype in(%d,%d) AND isis >0 ",
                    companyType, Constant.CUSTOMER_TYPE_TWO);
        }
        Query<Customers> query = customerDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where)).build();

        if (mCustomers != null) {
            mCustomers.clear();
        }
        mCustomers = query.list();
        if (mCustomers != null) {
            refreshUI();
        } else {
            mUpdateListViewListener.showMessage("没有数据,到基础数据里看看");
        }

    }

    public void search(String query) {
        if (mCustomers != null) {
            mCustomers.clear();
            mPage = 1;
        }
        String where = "";
       if (StringUtils.isHasChineseChar(query)) {
            where = "companyname like '%" + query + "%'";
        } else if (StringUtils.isLatter(query)) {
            where = "cpabbreviation like '%" + query + "%'";
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<Customers> userQuery = customerDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderAsc(CustomersDao.Properties.Companyname)
                .build();
        mCustomers = userQuery.list();
        refreshUI();
    }
}
